package com.lxf.clouduser.utils;

import org.springframework.stereotype.Component;

import javax.sound.sampled.*;
import java.io.File;
import java.nio.channels.Channel;

/**
 * @author 罗兴发
 * @data 2025/7/17 15:20
 * @description：语音通话-工具类
 */
@Component
public class AudioMsgUtils {

    private TargetDataLine microphone;
    private SourceDataLine speakers;

    //初始化
    public void initializeAudio() {
        try {
            // 获取麦克风输入流
            AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, true);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            microphone = (TargetDataLine) AudioSystem.getLine(info);
            microphone.open(format);
            microphone.start();

            // 获取扬声器输出流
            info = new DataLine.Info(SourceDataLine.class, format);
            speakers = (SourceDataLine) AudioSystem.getLine(info);
            speakers.open(format);
            speakers.start();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    //开始传输语音
    public void startStreaming() {
        new Thread(() -> {
            byte[] bytes = new byte[4096];
            int numBytesRead;
            while (true) {
                try {
                    // 读取麦克风数据并播放到扬声器
                    numBytesRead = microphone.read(bytes, 0, bytes.length);
                    if (numBytesRead > 0) {
                        speakers.write(bytes, 0, numBytesRead);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //结束语音聊天
    public void stopAudio(){
        microphone.stop();
        microphone.close();
        speakers.stop();
        speakers.close();
    }
}
